const { spawn } = require('child_process');
const { exec } = require('child_process');
const path = require('path');
const axios = require('axios');
const fs = require('fs');
const log = require('./logger');

class BackendService {
    constructor() {
        this.process = null;
        this.baseUrl = 'http://localhost:8000';
        this.isRunning = false;
    }

    startBackend(backendPath) {
        if (this.isRunning) {
            log('Backend is already running');
            return;
        }

        log(`Backend path: ${backendPath}`);

        const startScript = path.join(backendPath, 'timerposvc.exe');
        log(`Start script: ${startScript}`);

        try {
            // 直接启动可执行文件，传递数据库路径作为参数
            this.process = spawn(startScript, {
                cwd: backendPath,
                stdio: ['pipe', 'pipe', 'pipe'],
                env: {
                    ...process.env,
                    PYTHONUNBUFFERED: '1',
                    PYTHONIOENCODING: 'utf-8'
                }
            });

            this.isRunning = true;

            // 处理输出
            this.process.stdout.on('data', (data) => {
                log(`Backend stdout: ${data}`);
            });

            this.process.stderr.on('data', (data) => {
                log(`Backend stderr: ${data}`);
            });

            this.process.on('close', (code) => {
                log(`Backend process exited with code ${code}`);
                this.isRunning = false;
            });

            this.process.on('error', (err) => {
                log(`Failed to start backend: ${err}`);
                this.isRunning = false;
            });

        } catch (error) {
            log(`Error starting backend: ${error}`);
            throw error;
        }
    }

    stopBackend() {
        return new Promise((resolve) => {
            if (this.process) {
                // 首先尝试正常终止进程
                this.process.kill();
                
                // 使用 taskkill 确保进程被终止
                exec('taskkill /F /IM timerposvc.exe', (error) => {
                    if (error) {
                        log(`Error killing backend process: ${error}`);
                    } else {
                        log('Backend process terminated successfully');
                    }
                    this.process = null;
                    this.isRunning = false;
                    resolve();
                });
            } else {
                // 即使没有进程记录，也尝试清理可能残留的进程
                exec('taskkill /F /IM timerposvc.exe', () => {
                    this.isRunning = false;
                    resolve();
                });
            }
        });
    }

    async checkIfRunning() {
        try {
            const response = await axios.get(`${this.baseUrl}/api/test`, {
                timeout: 1000
            });
            if (response.status === 200) {
                log(`Backend service is ready: ${response.data}`);
                return true;
            }

        } catch (error) {
            log(`Backend service check failed: ${error.message}`);
            return false;
        }
        return false;
    }


    async waitForService(retries = 30, interval = 1000) {
        log('Waiting for backend service to start...');
        for (let i = 0; i < retries; i++) {
            try {
                const response = await axios.get(`${this.baseUrl}/api/test`, {

                    timeout: 1000
                });
                if (response.status === 200) {
                    log('Backend service is ready');
                    return true;
                }
            } catch (error) {
                log(`Attempt ${i + 1}/${retries} failed:${error.message}`);
                await new Promise(resolve => setTimeout(resolve, interval));
            }
        }

        log('Backend service failed to start after all retries');
        return false;

    }
}
const backendService = new BackendService();
module.exports = backendService; 